package com.yulongtian.offers.day202301;

/**
 * https://leetcode.cn/problems/trapping-rain-water/
 * 可
 * 接雨水 前后缀分解方法
 *
 * @author yulongTian
 * @create 2023-01-09 14:00
 */
public class Test01 {
    public static void main(String[] args) {
        int[] height = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1};
        System.out.println(trap(height));
    }

    public static int trap(int[] height) {
        int len = height.length;
        if (len < 3) {
            return 0;
        }
        //前缀最大值数组
        int[] pre = new int[len];
        pre[0] = height[0];

        for (int i = 1; i < height.length; i++) {
            pre[i] = Math.max(pre[i - 1], height[i]);
        }

        //后缀最大值数组
        int[] latter = new int[len];
        latter[len - 1] = height[len - 1];
        for (int i = len - 2; i >= 0; i--) {
            latter[i] = Math.max(height[i], latter[i + 1]);
        }
        int ans = 0;
        for (int i = 0; i < height.length; i++) {
            ans += Math.min(pre[i], latter[i]) - height[i];
        }

        return ans;
    }
}
